/**
 * 薪资意向
 */
import React from 'react';
import { InputItem, Modal, Toast } from 'antd-mobile';
import { Spin } from 'antd';
import { router, withRouter } from 'umi';
import { createForm } from 'rc-form';
import { useRequest, defaultFormatResult } from '@/hooks';
import { useFormChange } from '@/pages/RecruitEmail/hooks';
import { PageWrap, EditListItem, Button } from './components';
import { getRegisterDetail, updateSalary } from '../service';
import xIcon from '../images/icon-x.png';

const SalaryIntension = ({ location, form }) => {
    const { query } = location;
    const { getFieldProps } = form;
    const [submitLoading, setSubmitLoading] = React.useState(false);
    const [current, setCurrent] = React.useState();
    const { hasFormChange, initialForm } = useFormChange(form);

    console.log('getRegisterDetail---------SalaryIntension');
    const { loading, data: resumeDetail } = useRequest(() => getRegisterDetail(query?.nid), {
        ...defaultFormatResult,
        onSuccess: () => {
            initialForm();
        }
    });

    const handleLeftClick = () => {
        if (hasFormChange()) {
            Modal.alert('存在未保存的内容，确定退出吗？', '', [
                { text: '取消' },
                {
                    text: '确定',
                    onPress: () => {
                        history.goBack();
                    }
                }
            ]);
        } else {
            history.goBack();
        }
    };
    const handleSubmit = () => {
        form.validateFields(async (err, values) => {
            if (!err) {
                const params = {
                    expectMonthNumber: Number(values.expectMonthNumber),
                    expectSalary: Number(values.expectSalary),
                    id: resumeDetail?.id
                };
                setSubmitLoading(true);
                updateSalary(params)
                    .then(res => {
                        const { code, msg } = res;
                        if (code === 10000) {
                            // Toast.info('提交成功');
                            history.goBack();
                        } else {
                            Toast.info(msg);
                        }
                    })
                    .finally(() => {
                        setSubmitLoading(false);
                    });
            } else {
                const tempList = Object.values(err);
                if (tempList && tempList.length > 0) {
                    const { errors } = tempList[0];
                    Toast.info(errors[0]?.message);
                }
            }
        });
    };

    React.useEffect(() => {
        const values = form.getFieldsValue();
        if (current) {
            if (current.expectSalary !== values.expectSalary) {
                const finalParams = {
                    ...values,
                    monthSalary: (values.expectSalary / values.expectMonthNumber).toFixed(0)
                };
                setCurrent(finalParams);
                form.setFieldsValue(finalParams);
            } else if (
                current.monthSalary !== values.monthSalary ||
                current.expectMonthNumber !== values.expectMonthNumber
            ) {
                const finalParams = {
                    ...values,
                    expectSalary: (values.monthSalary * values.expectMonthNumber).toFixed(0)
                };
                setCurrent(finalParams);
                form.setFieldsValue(finalParams);
            }
        } else {
            setCurrent(values);
        }
    }, [form.getFieldsValue()]);

    const getMonthSalary = (s, m) => {
        if (s && m) {
            return (s / m).toFixed(0);
        }
        return '';
    };
    const formatSalaryInput = (val, int, decimal, type) => {
        let newVal = val
            .toString()
            .replace(/[^\d.]/g, '')
            .replace(/\.{2,}/g, '.')
            .replace(/^\./g, '')
            .replace('.', '$#$')
            .replace(/\./g, '')
            .replace('$#$', '.');
        const formatNewVal = newVal.split('.');
        if (formatNewVal.length === 2) {
            let intVal = newVal.split('.')[0];
            let decimalVal = newVal.split('.')[1];
            if (intVal.length > int) {
                intVal = intVal.substring(0, int);
            }
            if (decimalVal.length > decimal) {
                decimalVal = decimalVal?.substring(0, decimal);
            }
            newVal = `${intVal}.${decimalVal}`;
        } else {
            newVal = newVal.substring(0, int);
        }
        if (type === 'year') {
            form.setFieldsValue({ ...form.getFieldsValue(), expectSalary: newVal });
        } else {
            form.setFieldsValue({ ...form.getFieldsValue(), monthSalary: newVal });
        }
    };
    const monthInputVal = val => {
        formatSalaryInput(val, 8, 4);
    };
    const yearInputVal = val => {
        formatSalaryInput(val, 12, 8, 'year');
    };
    return (
        <PageWrap
            title="薪资意向"
            navbarProps={{ onLeftClick: handleLeftClick }}
            footer={
                <Button type="primary" loading={submitLoading} onClick={handleSubmit}>
                    保存
                </Button>
            }
        >
            <div style={{ padding: '0 16px' }}>
                <Spin spinning={loading}>
                    <EditListItem title="期望月薪" showArrow={false}>
                        <div style={{ display: 'flex', alignItems: 'center' }}>
                            <div style={{ width: 120, flexGrow: 1 }}>
                                <InputItem
                                    {...getFieldProps('monthSalary', {
                                        initialValue: getMonthSalary(
                                            resumeDetail?.expectSalary,
                                            resumeDetail?.expectMonthNumber
                                        ),
                                        rules: [{ required: true, message: '请输入月薪' }]
                                    })}
                                    type="money"
                                    moneyKeyboardAlign="left"
                                    // maxLength={8}
                                    clear
                                    placeholder="请输入月薪"
                                    onChange={val => monthInputVal(val)}
                                />
                            </div>
                            <img alt="" src={xIcon} style={{ width: 20, height: 20, marginRight: 20 }} />
                            <InputItem
                                {...getFieldProps('expectMonthNumber', {
                                    initialValue: resumeDetail?.expectMonthNumber
                                        ? `${resumeDetail?.expectMonthNumber}`
                                        : '12',
                                    rules: [
                                        { required: true, message: '请输入月份' },
                                        {
                                            validator(rule, value, callback) {
                                                if (value && value < 12) {
                                                    callback('月份不可小于12');
                                                }
                                                callback();
                                            }
                                        }
                                    ]
                                })}
                                type="number"
                                maxLength={3}
                                placeholder="请输入月份"
                                style={{ width: 120 }}
                            />
                            <div style={{ color: '#2a2f3c' }}>
                                {resumeDetail?.expectSalaryCurrencyCode || resumeDetail?.companyCurrencyCode}
                            </div>
                        </div>
                    </EditListItem>
                    <EditListItem title="期望年薪" showArrow={false}>
                        <div style={{ display: 'flex', alignItems: 'center' }}>
                            <div style={{ flexGrow: 1 }}>
                                <InputItem
                                    {...getFieldProps('expectSalary', {
                                        initialValue: resumeDetail?.expectSalary ? `${resumeDetail?.expectSalary}` : '',
                                        rules: [{ required: true, message: '请输入期望年薪' }]
                                    })}
                                    type="money"
                                    moneyKeyboardAlign="left"
                                    // maxLength={8}
                                    clear
                                    placeholder="请输入期望年薪"
                                    onChange={val => yearInputVal(val)}
                                />
                            </div>
                            <div style={{ color: '#2a2f3c', flexGrow: 0 }}>
                                {resumeDetail?.expectSalaryCurrencyCode || resumeDetail?.companyCurrencyCode}
                            </div>
                        </div>
                    </EditListItem>
                </Spin>
            </div>
        </PageWrap>
    );
};

export default withRouter(createForm()(SalaryIntension));
